export default {
  namespaced:true,
  state:()=>({
    // 购物车内数据
    cart :JSON.parse(uni.getStorageSync('cart') || '[]')
  }),
  // 方法
  mutations:{
    // 加入购物车功能
    addToCart(state,goods){
      // 判断现在有没有这件商品，如果有增加数量，没有直接添加
      // 会返回一个对象或者undefined
      const findResult =  state.cart.find(x=>x.goods_id === goods.goods_id)
      if(!findResult){
        state.cart.push(goods)
      }else{
        findResult.goods_count++
      }
      // 持久化
      this.commit('m_cart/saveToStorage')
    },
    // 持久化本地
    saveToStorage(state){
      uni.setStorageSync('cart',JSON.stringify(state.cart))
    },
    // 修改选中状态
    undataGoodsState(state,goods){
      const findResult = state.cart.find(x=>x.goods_id === goods.goods_id)
      if(findResult){
        findResult.goods_state = goods.goods_state
        this.commit('m_cart/saveToStorage')
      }
    },
    // 修改数量
    undataGoodsNum(state,goods){
      const findResult = state.cart.find(x=>x.goods_id === goods.goods_id)
      if(findResult){
        findResult.goods_count = goods.goods_count
        // 持久化
        this.commit('m_cart/saveToStorage')
      }
    },
    // 删除购物车商品
    removeGoodsById(state,goods_id){
      state.cart = state.cart.filter(x=>x.goods_id!==goods_id)
      this.commit('m_cart/saveToStorage')
    },
    // 更新全选勾选效果
    undataAllGoodsState(state,newState){
      // 遍历所有state 给新值
      state.cart.forEach(x => x.goods_state = newState)
      this.commit('m_cart/saveToStorage')
    },
    // 
  },
  // 异步
  // actions:{},
  // 属性
  getters:{
    // 总数量
    total(state){
      let c = 0
      state.cart.forEach(goods=>c+=goods.goods_count)
      return c
    },
    //勾选的商品数量 
    checkedCount(state){
      return state.cart.filter(x=>x.goods_state).reduce((total,item)=>total+=item.goods_count,0)
    },
    // 计算勾选商品价格
    checkedGoodsAmount(state){
      // 筛选勾选 计算价格 结尾保留
      return state.cart.filter(x=>x.goods_state).reduce((total,item)=>total += item.goods_price*item.goods_count,0).toFixed(2)
    },
    // 
  }
}